package br.com.d2g.realestate.controller;

import br.com.d2g.realestate.persistence.Announce;
import br.com.d2g.realestate.controller.util.JsfUtil;
import br.com.d2g.realestate.controller.util.PaginationHelper;
import br.com.d2g.realestate.facade.AgentFacade;
import br.com.d2g.realestate.facade.AnnounceFacade;

import br.com.d2g.realestate.facade.ClientFacade;
import br.com.d2g.realestate.facade.FurnitureFacade;
import br.com.d2g.realestate.facade.GardenFacade;
import br.com.d2g.realestate.facade.OfferFacade;
import br.com.d2g.realestate.facade.OwnerFacade;
import br.com.d2g.realestate.facade.UserFacade;
import br.com.d2g.realestate.persistence.Furniture;
import br.com.d2g.realestate.persistence.Garden;
import br.com.d2g.realestate.persistence.Offer;
import br.com.d2g.realestate.webservice.client.ExchangeRate;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "announceController")
@SessionScoped
public class AnnounceController implements Serializable {

    private Announce current;
    private DataModel items = null;
    @EJB
    private UserFacade userFacade;
    @EJB
    private ClientFacade clientFacade;
    @EJB
    private AgentFacade agentFacade;
    @EJB
    private OwnerFacade ownerFacade;
    @EJB
    private OfferFacade offerFacade;
    @EJB
    private GardenFacade gardenFacade;
    @EJB
    private FurnitureFacade furnitureFacade;
    @EJB
    private br.com.d2g.realestate.facade.AnnounceFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String searchAddress;
    private String searchPostcode;
    private Integer searchMinNumberBathroom;
    private Integer searchMaxNumberBathroom;
    private Integer searchMinNumberBedroom;
    private Integer searchMaxNumberBedroom;
    private String searchFurnished;
    private String searchType;
    private String searchGarden;
    private Long searchMinPrice;
    private Long searchMaxPrice;
    private String offerClient;
    private Long offerValue;
    private String currency;
    

    public AnnounceController() {
    }

    public String search() {
        return null;
    }

    public Announce getSelected() {
        if (current == null) {
            current = new Announce();
            selectedItemIndex = -1;
        }
        return current;
    }

    private AnnounceFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().countAnnounceByCriteria(searchType, searchAddress, searchPostcode,
                            searchMinNumberBathroom, searchMaxNumberBathroom, searchMinNumberBedroom, searchMaxNumberBedroom,
                            searchFurnished, searchType, searchGarden, searchMinPrice, searchMaxPrice);
//                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().searchAnnounceByCriteria(searchType, searchAddress, searchPostcode,
                            searchMinNumberBathroom, searchMaxNumberBathroom, searchMinNumberBedroom, searchMaxNumberBedroom,
                            searchFurnished, searchType, searchGarden, searchMinPrice, searchMaxPrice, new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
//                                        return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Announce) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Announce();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AnnounceCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Announce) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AnnounceUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Announce) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AnnounceDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * @return the searchAddress
     */
    public String getSearchAddress() {
        return searchAddress;
    }

    /**
     * @param searchAddress the searchAddress to set
     */
    public void setSearchAddress(String searchAddress) {
        this.searchAddress = searchAddress;
    }

    /**
     * @return the searchPostcode
     */
    public String getSearchPostcode() {
        return searchPostcode;
    }

    /**
     * @param searchPostcode the searchPostcode to set
     */
    public void setSearchPostcode(String searchPostcode) {
        this.searchPostcode = searchPostcode;
    }

    /**
     * @return the searchMinNumberBathroom
     */
    public Integer getSearchMinNumberBathroom() {
        return searchMinNumberBathroom;
    }

    /**
     * @param searchMinNumberBathroom the searchMinNumberBathroom to set
     */
    public void setSearchMinNumberBathroom(Integer searchMinNumberBathroom) {
        this.searchMinNumberBathroom = searchMinNumberBathroom;
    }

    /**
     * @return the searchMaxNumberBathroom
     */
    public Integer getSearchMaxNumberBathroom() {
        return searchMaxNumberBathroom;
    }

    /**
     * @param searchMaxNumberBathroom the searchMaxNumberBathroom to set
     */
    public void setSearchMaxNumberBathroom(Integer searchMaxNumberBathroom) {
        this.searchMaxNumberBathroom = searchMaxNumberBathroom;
    }

    /**
     * @return the searchMinNumberBedroom
     */
    public Integer getSearchMinNumberBedroom() {
        return searchMinNumberBedroom;
    }

    /**
     * @param searchMinNumberBedroom the searchMinNumberBedroom to set
     */
    public void setSearchMinNumberBedroom(Integer searchMinNumberBedroom) {
        this.searchMinNumberBedroom = searchMinNumberBedroom;
    }

    /**
     * @return the searchMaxNumberBedroom
     */
    public Integer getSearchMaxNumberBedroom() {
        return searchMaxNumberBedroom;
    }

    /**
     * @param searchMaxNumberBedroom the searchMaxNumberBedroom to set
     */
    public void setSearchMaxNumberBedroom(Integer searchMaxNumberBedroom) {
        this.searchMaxNumberBedroom = searchMaxNumberBedroom;
    }

    /**
     * @return the searchFurnished
     */
    public String getSearchFurnished() {
        return searchFurnished;
    }

    /**
     * @param searchFurnished the searchFurnished to set
     */
    public void setSearchFurnished(String searchFurnished) {
        this.searchFurnished = searchFurnished;
    }

    /**
     * @return the searchType
     */
    public String getSearchType() {
        return searchType;
    }

    /**
     * @param searchType the searchType to set
     */
    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }

    /**
     * @return the searchGarden
     */
    public String getSearchGarden() {
        return searchGarden;
    }

    /**
     * @param searchGarden the searchGarden to set
     */
    public void setSearchGarden(String searchGarden) {
        this.searchGarden = searchGarden;
    }

    /**
     * @return the searchMinPrice
     */
    public Long getSearchMinPrice() {
        return searchMinPrice;
    }

    /**
     * @param searchMinPrice the searchMinPrice to set
     */
    public void setSearchMinPrice(Long searchPrice) {
        this.searchMinPrice = searchPrice;
    }

    /**
     * @return the searchMaxPrice
     */
    public Long getSearchMaxPrice() {
        return searchMaxPrice;
    }

    /**
     * @param searchMaxPrice the searchMaxPrice to set
     */
    public void setSearchMaxPrice(Long searchMaxPrice) {
        this.searchMaxPrice = searchMaxPrice;
    }

    public String[] getPopulateGardenDropDownList() {
        List<Garden> gardenList = gardenFacade.findAll();
        String[] stringGardenList = new String[gardenList.size() + 1];
        stringGardenList[0] = "";
        for (int i = 0; i < gardenList.size(); i++) {
            stringGardenList[i + 1] = gardenList.get(i).getType();
        }
        return stringGardenList;
    }

    public String[] getPopulateFurnitureDropDownList() {
        List<Furniture> furnitureList = furnitureFacade.findAll();
        String[] stringFurnitureList = new String[furnitureList.size() + 1];
        stringFurnitureList[0] = "";
        for (int i = 0; i < furnitureList.size(); i++) {
            stringFurnitureList[i + 1] = furnitureList.get(i).getType();
        }
        return stringFurnitureList;
    }

    /**
     * @return the offerClient
     */
    public String getOfferClient() {
        return offerClient;
    }

    /**
     * @param offerClient the offerClient to set
     */
    public void setOfferClient(String offerClient) {
        this.offerClient = offerClient;
    }

    /**
     * @return the offerValue
     */
    public Long getOfferValue() {
        return offerValue;
    }

    /**
     * @param offerValue the offerValue to set
     */
    public void setOfferValue(Long offerValue) {
        this.offerValue = offerValue;
    }

    public String[] getAllCurrencies() {
        List<ExchangeRate> exchangeRateList = getFacade().getAllCurrencies();
        //String currency = "";
        String[] currencyArray = new String[exchangeRateList.size()];
        for (int i = 0; i < exchangeRateList.size(); i++) {
            currencyArray[i] = exchangeRateList.get(i).getCurrency();
        }
//        ExchangeRate exchangeRate = getFacade().getGBPConvertionRate("BRL");
//        System.out.printf("xml: %s", exchangeRateList.toString());
        this.setCurrency("GBP");
        return currencyArray;
//        return null;
    }

    public String makeOffer() {
        try {
            ExchangeRate exchangeRate = getFacade().getGBPConvertionRate(currency);
            Offer offer = new Offer();
            Double offerInGBPDouble = offerValue.doubleValue() * exchangeRate.getRateToGbp();
            offer.setAmount(offerInGBPDouble.longValue());                      
//            offer.setAmount(offerValue);
            if (UserController.isAgent()) {
                offer.setClientUsername(clientFacade.find(offerClient));
            }
            offer.setClientUsername(clientFacade.find(UserController.getLoggedUserName()));
            offer.setIdAnnounce(current);
            offer.setOfferDate(new Date());
            offerFacade.create(offer);
            JsfUtil.addSuccessMessage("The offer has been placed!!");
            return null;
        } catch (Exception ex) {
            JsfUtil.addErrorMessage(ex, ex.getLocalizedMessage());
            return null;
        }
    }

    /**
     * @return the currency
     */
    public String getCurrency() {
        return currency;
    }

    /**
     * @param currency the currency to set
     */
    public void setCurrency(String currency) {
        this.currency = currency;
    }

    @FacesConverter(forClass = Announce.class)
    public static class AnnounceControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            AnnounceController controller = (AnnounceController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "announceController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Announce) {
                Announce o = (Announce) object;
                return getStringKey(o.getIdAnnounce());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + AnnounceController.class.getName());
            }
        }
    }
}
